package cc.idoone.codegen.table;

import cc.idoone.codegen.config.DataSourceConfig;
import cc.idoone.codegen.table.query.MysqlTableInfoQuery;
import cc.idoone.codegen.table.query.OracleTableInfoQuery;
import cc.idoone.codegen.table.query.PostgresqlTableInfoQuery;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @auther hemj
 * @since 2020/8/25
 */
public abstract class TableInfoQuery {
	protected DataSourceConfig dataSource;
	protected Connection conn;

	/**
	 * 创建数据库连接对象
	 */
	protected Connection getConn() throws ClassNotFoundException, SQLException {
		if (conn == null) {
			Class.forName(dataSource.getDriverClassName());
			conn = DriverManager.getConnection(dataSource.getUrl(), dataSource.getUsername(), dataSource.getPassword());
		}
		return conn;
	}

	public static TableInfoQuery getInstance(DataSourceConfig dataSource) {
		if (dataSource.getDriverClassName().contains("postgresql")) {
			return new PostgresqlTableInfoQuery(dataSource);
		} else if (dataSource.getDriverClassName().contains("mysql")) {
			return new MysqlTableInfoQuery(dataSource);
		} else if (dataSource.getDriverClassName().contains("oracle")) {
			return new OracleTableInfoQuery(dataSource);
		} else {
			throw new RuntimeException("Unknown JDBC driver class name");
		}
	}

	/**
	 * 数据库表信息
	 */
	public abstract TableInfo queryTableInfo(String tableName) throws ClassNotFoundException, SQLException;
}
